/* eslint-disable max-len */
/* eslint-disable @typescript-eslint/no-unused-expressions */
/* eslint-disable no-lone-blocks */
import React, {
  useEffect, useState, useMemo, useCallback,
} from 'react';
import { observer } from 'mobx-react-lite';
import map from 'lodash/map';
import { Tooltip } from 'choerodon-ui/pro/lib';
import forEach from 'lodash/forEach';
// @ts-ignore
import queryString from 'query-string';
import { useLocation } from 'react-router';
import Status from '../../../deployment-list/components/StatusTag';
import BasicConfigurationCard from '@/routes/continuous-deployment/components/basicConfigurationCard';
import { defaultBasicConfigurationData } from '../../../deployment-operation/CONSTANTS';
import { useDetailStore } from '../../stores/index';
import useGetPersonalToken from '../../../../hooks/useGetPersonalToken';
import './index.less';

interface Iprops{

}
const Index:React.FC<Iprops> = (props:Iprops) => {
  const { pipDetailDs, basicConfigurationData, projectId } = useDetailStore();
  const pipDs:any = pipDetailDs.toData()[0];
  // 避免当我们的对象为undefined报错
  const { stageList } = pipDs || {};
  const { search } = useLocation();
  const [personalToken] = useGetPersonalToken(projectId);
  // 定义划线结构
  const [leftLineDom, setLeftLineDom] = useState([]);
  const [rightLineDom, setRightLineDom] = useState([]);
  // 模块连接线样式
  useEffect(() => {
    const leftList = [] as any;
    const rightList = [] as any;
    forEach(stageList, ({ jobList, id }:any, stageIndex:number) => {
      forEach(jobList, (data, index:number) => {
        const leftItem = (
          <div
            className="c7ncd-pipelines-detail-job-rect-left"
            style={getJobRectStyle(stageIndex, index)}
          />
        );
        const rightItem = (
          <div
            className="c7ncd-pipelines-detail-job-rect-right"
            style={getJobRectStyle(stageIndex, index)}
          />
        );
        if (leftList[stageIndex]) {
          leftList[stageIndex].push(leftItem);
          rightList[stageIndex].push(rightItem);
        } else {
          leftList[stageIndex] = [leftItem];
          rightList[stageIndex] = [rightItem];
        }
      });
    });
    setLeftLineDom(leftList);
    setRightLineDom(rightList);
  }, [(pipDs && pipDs.id)]);
  function getJobRectStyle(stageIndex:number, index:number) {
    let sum = 0;
    for (let i = 0; i < index; i += 1) {
      // @ts-ignore
      sum += document.getElementById(`${'idd'}-${stageIndex}-job-${i}`) ? document.getElementById(`${'idd'}-${stageIndex}-job-${i}`)?.offsetHeight + 30 : 0;
    }
    return { height: sum };
  }
  // 渲染job名称
  const getJobName = (type:string, name:string) => {
    const Type:any = {
      cd_chart_deploy: 'chart包',
      cd_audit: '人工卡点',
    };
    if (type) {
      return (
        <span>
          【
          {Type[type]}
          】
          {name}
        </span>
      );
    }
    return (
      <span>{name}</span>
    );
  };
  // 渲染每一个模块的内容
  const renderContent = (type:string, auditConfig?:any, chartDeployCfg?:any) => {
    if (type === 'cd_chart_deploy') {
      if (chartDeployCfg) {
        return (
          <div className="c7ncd-pipelines-detail-job-content-detail c7ncd-pipelines-detail-job-content-details">
            <div>
              应用服务：
              {chartDeployCfg.appServiceName ? (
                <Tooltip title={chartDeployCfg.appServiceName} placement="topLeft">
                  {chartDeployCfg.appServiceName}
                </Tooltip>
              ) : '-'}
            </div>
            <div>
              版本类型：
              {chartDeployCfg.version ? <Tooltip title={chartDeployCfg.version} placement="topLeft">{chartDeployCfg.version}</Tooltip> : '-'}
            </div>
            <div>
              部署环境：
              {chartDeployCfg.envName ? <Tooltip title={chartDeployCfg.envName} placement="topLeft">{chartDeployCfg.envName}</Tooltip> : '-'}
            </div>
          </div>
        );
      }
      return '';
    } if (type === 'cd_audit') {
      if (auditConfig) {
        return (
          <div className="c7ncd-pipelines-detail-job-content-deatil">
            <div>
              审核人员：
              {auditConfig.iamUserDTOS && auditConfig.iamUserDTOS.length !== 0 ? auditConfig.iamUserDTOS
                .map((item:any, index:number) => (
                  <span style={{
                    background: 'rgba(15,19,88,0.06)', display: 'inline-block', marginRight: '3px', padding: '0 4px', marginTop: '3px',
                  }}
                  >
                    { item.realName }
                  </span>
                )) : '-'}
            </div>
            <div>
              审核模式：
              {auditConfig.countersigned ? '会签' : '或签'}
            </div>
          </div>
        );
      }
      return '';
    }
    return '';
  };
  return (
    <div className="c7ncd-pipelines">
      <div className="c7ncd-pipelines-header-title">
        <div className="c7ncd-pipelines-header-title-info">
          基本信息
        </div>
        <div className="c7ncd-pipelines-header-title-stage">
          阶段
        </div>
      </div>
      <div className="c7ncd-pipelines-detail">
        <div className="c7ncd-pipelines-detail-info">
          <div className="c7ncd-pipelines-detail-info-detail">
            <div className="c7ncd-pipelines-detail-info-detail-line" />
            <div className="c7ncd-pipelines-detail-info-detail-title">
              <div>
                <Tooltip title={pipDs && pipDs.name} placement="top">
                  {pipDs && pipDs.name}
                </Tooltip>
              </div>
              <div>
                <Status status={pipDs && pipDs.enable} />
              </div>
            </div>
            <div className="c7ncd-pipelines-detail-info-detail-content">
              {
                  Object.keys(basicConfigurationData || defaultBasicConfigurationData).length ? (
                    <BasicConfigurationCard
                      basicConfigurationData={basicConfigurationData || defaultBasicConfigurationData}
                      personalToken={personalToken}
                    />
                  ) : ''
                }
            </div>
          </div>
        </div>
        <div className="c7ncd-pipelines-detail-content">
          {stageList && map(stageList, ({
            id: stageId, name: stageName, jobList, type: stageType = 'CI', parallel, triggerType = 'auto',
          }:any, stageIndex:number) => (
            <div className="c7ncd-pipelines-detail-stage" key={`${stageId}-${stageIndex}`}>
              <div className="c7ncd-pipelines-detail-stage-title">
                <Tooltip title={stageName} placement="top">
                  <span className="c7ncd-pipelines-detail-stage-title-text">{stageName}</span>
                </Tooltip>
              </div>
              <div className="c7ncd-pipelines-detail-stage-line" />
              {stageIndex !== 0 ? (
                <div className="c7ncd-pipelines-detail-stage-arrow">
                  {triggerType === 'auto' ? (
                    <svg xmlns="http://www.w3.org/2000/svg" width="28" height="9" viewBox="0 0 28 9">
                      <path fill="#6887E8" d="M511.5,131 L520.5,135.5 L511.5,140 L511.5,136 L493,136 L493,135 L511.5,135 L511.5,131 Z" transform="translate(-493 -131)" />
                    </svg>
                  ) : (
                    <svg xmlns="http://www.w3.org/2000/svg" width="28" height="9" viewBox="0 0 26 9">
                      <path fill="#F1B42D" d="M917.5,130 L926.5,134.5 L917.5,139 L917.5,135 L913.5,135 L913.5,134 L917.5,134 L917.5,130 Z M905.5,134 L905.5,135 L901.5,135 L901.5,134 L905.5,134 Z M911.5,134 L911.5,135 L907.5,135 L907.5,134 L911.5,134 Z" transform="translate(-901 -130)" />
                    </svg>
                  )}
                </div>
              ) : null}
              {jobList && map(jobList, ({
                id: jobId, name: jobName, chartDeployCfg, auditConfig, type: jobType,
              }:any, index:number) => (
                <div key={`${stageId}-${jobId}`}>
                  {index && leftLineDom[stageIndex] ? leftLineDom[stageIndex][index] : null}
                  <div className={`c7ncd-pipelines-detail-job c7ncd-pipelines-detail-job-${stageType}`} id={`${'idd'}-${stageIndex}-job-${index}`}>
                    <div className="c7ncd-pipelines-detail-job-title">
                      <Tooltip title={jobName} placement="top">
                        {getJobName(jobType, jobName)}
                      </Tooltip>
                    </div>
                    <div className="c7ncd-pipelines-detail-job-content">
                      {renderContent(jobType, auditConfig, chartDeployCfg)}
                    </div>
                  </div>
                  {index && stageIndex !== stageList.length - 1 && rightLineDom[stageIndex] ? rightLineDom[stageIndex][index] : null}
                </div>
              ))}
            </div>
          ))}
        </div>
      </div>
    </div>
  );
};
export default observer(Index);
